<?php
/*
 * Gallery - a web based photo album viewer and editor
 * Copyright (C) 2000-2002 Bharat Mediratta
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

// Hack prevention.
if (!empty($_REQUEST["GALLERY_BASEDIR"])) {
	print "Security violation\n";
	exit;
}
require_once('./init.php'); 
$myts =& MyTextSanitizer::getInstance();
// Hack check
if (!$gallery->user->canReadAlbum($gallery->album)) {
	header("Location: " . makeAlbumUrl());
	return;
}
if (!$gallery->album->isLoaded()) {
	header("Location: " . makeAlbumUrl());
	return;
}
if (!isset($page)) {
	$page = @$gallery->session->albumPage[$gallery->album->fields["name"]];
	if (!$page) {
		$page = 1;
	}
} else {
	$gallery->session->albumPage[$gallery->album->fields["name"]] = $page;
}
$albumName = $gallery->session->albumName;
if (!isset($gallery->session->viewedAlbum[$albumName])) {
	$gallery->session->viewedAlbum[$albumName] = 1;
	$gallery->album->incrementClicks();
} 
$rows = $gallery->album->fields["rows"];
$cols = $gallery->album->fields["cols"];
$numPhotos = $gallery->album->numPhotos($gallery->user->canWriteToAlbum($gallery->album));
$perPage = $rows * $cols;
$maxPages = max(ceil($numPhotos / $perPage), 1);
if ($page > $maxPages) {
	$page = $maxPages;
}
$start = ($page - 1) * $perPage + 1;
$end = $start + $perPage;
$nextPage = $page + 1;
if ($nextPage > $maxPages) {
	$nextPage = 1;
        $last = 1;
}
$previousPage = $page - 1;
if ($previousPage == 0) {
	$previousPage = $maxPages;
	$first = 1;
}
$bordercolor = $gallery->album->fields["bordercolor"];
$imageCellWidth = floor(100 / $cols) . "%";
$fullWidth="100%";
$navigator["page"] = $page;
$navigator["pageVar"] = "page";
$navigator["maxPages"] = $maxPages;
$navigator["fullWidth"] = $fullWidth;
$navigator["url"] = makeAlbumUrl($gallery->session->albumName);
$navigator["spread"] = 5;
$navigator["bordercolor"] = $bordercolor;
$breadCount = 0;
$breadtext = array();
$pAlbum = $gallery->album;
do {
  if (!strcmp($pAlbum->fields["returnto"], _NO)) {
    break;
  }
  $pAlbumName = $pAlbum->fields['parentAlbumName'];
  if ($pAlbumName) {
    $pAlbum = new Album();
    $pAlbum->load($pAlbumName);
    $breadtext[$breadCount] = "<a href=\"" . makeAlbumUrl($pAlbumName) .
      "\">" . $pAlbum->fields['title'] . "</a>";
  } else {
    //-- we're at the top! ---
    $breadtext[$breadCount] = "<a href=\"" . makeGalleryUrl("albums.php") .
      "\">" . $gallery->app->galleryTitle . "</a>"; 
  }
  $breadCount++;
} while ($pAlbumName);
//-- we built the array backwards, so reverse it now ---
for ($i = count($breadtext) - 1; $i >= 0; $i--) {
	$breadcrumb["text"][] = $breadtext[$i];
}
// $breadcrumb["text"][] = "<b>".$myts->displayTarea($myts->stripSlashesGPC($gallery->album->fields['title']),1)."</b>";
$breadcrumbfocus = "<b>".$myts->displayTarea($myts->stripSlashesGPC($gallery->album->fields['title']),1)."</b>";
$javascript = '
  <script type="text/javascript">
  <!--
  var statusWin;
  function showProgress() {
	statusWin = '.popup_status("progress_uploading.php").'
  }

  function hideProgress() {
	if (typeof(statusWin) != "undefined") {
		statusWin.close();
		statusWin = void(0);
	}
  }

  function hideProgressAndReload() {
	hideProgress();
	history.go(0);
  }
  function imageEditChoice(selected_select) {
	  var sel_index = selected_select.selectedIndex;
	  var sel_value = selected_select.options[sel_index].value;
	  selected_select.options[0].selected = true;
	  selected_select.blur();
	  '.popup("sel_value", 1).'
  } 
  // --> 
  </script>';
$xoopsOption['template_main'] = 'xoopsgallery_viewalbum.html';
include_once XOOPS_ROOT_PATH.'/header.php';
$xoopsTpl->assign('gallery_version', $gallery->version);
$xoopsTpl->assign('lang_page', _XG_PAGE);
$xoopsTpl->assign('javascript', $javascript);
$xoopsTpl->assign('album_title', $myts->displayTarea($myts->stripSlashesGPC($gallery->album->fields['title']),1));
$xoopsTpl->assign('album_desc', $myts->displayTarea($myts->stripSlashesGPC($gallery->album->fields['description']),1));
function showChoice($label, $target, $args) {
    global $gallery;
    if (empty($args['set_albumName'])) {
	$args['set_albumName'] = $gallery->session->albumName;
    }
	return "<option value='" . makeGalleryUrl($target, $args) . "'>$label</option>";
}
$statsText = "<b>";
if ($numPhotos == 1) {  
	$statsText .= _XG_ONE_PHOTO_IN_ALBUM;
} else {
	$statsText .= $numPhotos._XG_ITEMS_IN_ALBUM;
	if ($maxPages > 1) {
		$statsText .= _XG_ON. pluralize($maxPages, _XG_STATPAGE);
	}
}
if ($gallery->user->canWriteToAlbum($gallery->album)) {
	$hidden = $gallery->album->numHidden();
	$verb = _XG_ARE;
	if ($hidden == 1) {
		$verb = _XG_IS;
	}
	if ($hidden) {
		$statsText .= " (".$hidden.$verb._XG_HIDDEN.")";
	}
} 
$statsText .="</b>";
$adminHasCommands = false;
$adminCommands = "";
if ($gallery->user->canAddToAlbum($gallery->album)) {
	$adminCommands .= '<a href="#" onClick="'.popup("add_photos.php?set_albumName=".$gallery->session->albumName).'">['._XG_ADD_PHOTOS.']</a>&nbsp;';
	$adminHasCommands = true;
}
if ($gallery->user->canCreateSubAlbum($gallery->album)) {
	$adminCommands .= '<a href="'.doCommand("new-album", 
						array("parentName" => $gallery->session->albumName),
						 "view_album.php") .
						 '">['._XG_ADD_NEW_NESTED_ALBUM.']</a>&nbsp;';
	$adminHasCommands = true;
}
if ($gallery->user->canChangeTextOfAlbum($gallery->album)) {
	$adminCommands .= '<a href='.makeGalleryUrl("captionator.php", array("page" => $page, "perPage" => $perPage)).'>['._XG_CAPTIONS.']</a>&nbsp;';
	$adminHasCommands = true;
}
if ($gallery->user->canWriteToAlbum($gallery->album)) {
	if ($gallery->album->numPhotos(1)) {
	        $adminCommands .= '<a href="#" onClick="'.popup("sort_album.php?set_albumName=" .
				$gallery->session->albumName).
				'">['._XG_SORT.']</a>&nbsp;';
	        $adminCommands .= '<a href="#" onClick="'.popup("resize_photo.php?set_albumName=" .
				$gallery->session->albumName . "&index=all").
				'">['._XG_RESIZE_ALL.']</a>&nbsp;';
	        $adminCommands .= '<a href="#" onClick="'.popup("do_command.php?cmd=remake-thumbnail&set_albumName=" .
				$gallery->session->albumName . "&index=all").
				'">['._XG_REBUILD_THUMBS.']</a>&nbsp;&nbsp;'; 
	}
        $adminCommands .= '<a href="#" onClick="'.popup("edit_appearance.php?set_albumName=" .
			$gallery->session->albumName).
			'">['._XG_PROPERTIES.']</a>&nbsp;';
	$adminHasCommands = true;
}
if ($gallery->user->isAdmin() || $gallery->user->isOwnerOfAlbum($gallery->album)) {
        $adminCommands .= '<a href="#" onClick="'.popup("album_permissions.php?set_albumName=" .
			$gallery->session->albumName).
			'">['._XG_PERMISSIONS.']</a>&nbsp;';
		$adminHasCommands = true;
}
// old first line  $adminCommands .= '<a href=' .
$slideshowCommand = '<a href=' . 
	                makeGalleryUrl("slideshow.php",
		            array("set_albumName" => $albumName)) .
	                '>['._XG_SLIDESHOW.']</a>&nbsp;';
if (!$GALLERY_EMBEDDED_INSIDE) {
	if ($gallery->user->isLoggedIn()) {
	        $adminCommands .= "<a href=" .
					doCommand("logout", array(), "view_album.php", array("page" => $page)) .
				  ">["._XG_LOGOUT."]</a>";
	} else {
		$adminCommands .= '<a href="#" onClick="'.popup("login.php").'">['._XG_LOGIN.']</a>';
	} 
}
//$adminCommands .= "</span>";
/*  old admin box
$xoopsTpl->assign('adminbox', $adminText.'<br />'.$adminCommands);
$xoopsTpl->assign('adminHasCommands', $adminHasCommands);

* New:  statsbox (adminText part of adminbox) replace statsText with adminText
*       adminbox (admin functions that are allowed)
*       slideshowbox (slideshow function) replace "slideshowCommand" with "adminCommands ."
* Why: Stats and slideshow are not admin functions you can limit access thru template file
*      Also you can now put stats and slideshow where you want it on the page!

*/
$xoopsTpl->assign('adminHasCommands', $adminHasCommands);
$xoopsTpl->assign('adminbox', $adminCommands);
$xoopsTpl->assign('statsbox', $statsText);
$xoopsTpl->assign('slideshowbox', $slideshowCommand);
$xoopsTpl->assign('breadfocusbox', $breadcrumbfocus);
$breadcrumb["top"] = true;
if (strcmp($gallery->album->fields["returnto"], _NO) 
   || ($gallery->album->fields["parentAlbumName"])) {
	ob_start();
	include($GALLERY_BASEDIR . "layout/breadcrumb.inc");
	$xoopsTpl->assign('breadcrumb', ob_get_contents());
	ob_end_clean();
}
ob_start();
include($GALLERY_BASEDIR . "layout/navigator.inc");
$xoopsTpl->assign('navbar', ob_get_contents());
ob_end_clean();
$image_handler =& xoops_getmodulehandler('image');
$album_images =& $image_handler->getObjects(new Criteria('image_albumdir', $gallery->session->albumName), true);
$numPhotos = $gallery->album->numPhotos(1);
if ($numPhotos) {
	$rowCount = 0;
	// Find the correct starting point, accounting for hidden photos
	$rowStart = 0;
	$cnt = 0;
	while ($cnt < $start) {
		$rowStart = getNextPhoto($rowStart);
		$cnt++;
	}
	while ($rowCount < $rows) {
		/* Do the picture row */
		$i = $rowStart;
		$j = 1;
		$pictures = array();
		while ($j <= $cols && $i <= $numPhotos) {
			$picture = array();
			//-- put some parameters for the wrap files in the global object ---
			//$gallery->html_wrap['borderColor'] = $bordercolor;
			//$gallery->html_wrap['borderWidth'] = $borderwidth;
			//$gallery->html_wrap['pixelImage'] = $imageDir . "/pixel_trans.gif";
			$scaleTo = $gallery->album->fields["thumb_size"];
			//list($iWidth, $iHeight) = $gallery->album->getThumbDimensions($i, $scaleTo);
			//if ($iWidth == 0) {
			//    $iWidth = $gallery->album->fields["thumb_size"];
			//}
			//if ($iHeight == 0) {
			//    $iHeight = 100;
			//}
			//$gallery->html_wrap['thumbWidth'] = $iWidth;
			//$gallery->html_wrap['thumbHeight'] = $iHeight;
			$id = $gallery->album->getPhotoId($i);
			$picture['index'] = $i;
			if ($gallery->album->isMovie($id)) {
				$picture['image'] = $gallery->album->getThumbnailTag($i);
				$picture['link'] = $gallery->album->getPhotoPath($i);
			} elseif ($gallery->album->isAlbumName($i)) {
				$myAlbumName = $gallery->album->isAlbumName($i);
				$myAlbum = new Album();
				$myAlbum->load($myAlbumName);

				$picture['image'] = $myAlbum->getHighlightAsThumbnailTag($scaleTo);
				$picture['link'] = makeAlbumUrl($myAlbumName);

			} else {
				$photo = $gallery->album->getPhoto($i);
				$picture['image'] = $gallery->album->getThumbnailTag($i);
				$xoops_imageid = $photo->image->getXoopsImageId();
				$xoops_imageid = !empty($xoops_imageid) ? intval($xoops_imageid) : 0;
				$picture['link'] = makeAlbumUrl($gallery->session->albumName, $id, array('xoops_imageid' => $xoops_imageid));
			}
			$pictures[] =& $picture;
			unset($picture);
			$j++; 
			$i = getNextPhoto($i);
		}
		/* Now do the caption row */
		$captions = array();
		$adminforms = array();
		$i = $rowStart;
		$j = 1;
		while ($j <= $cols && $i <= $numPhotos) {
			
			if ($gallery->album->isAlbumName($i)) {
			    $iWidth = $gallery->album->fields['thumb_size'];
			} else {
			    list($iWidth, $iHeight) = $gallery->album->getThumbDimensions($i);
			}
			// put form outside caption to compress lines
			$adminform = '';
            if (($gallery->user->canDeleteFromAlbum($gallery->album)) ||
                                    ($gallery->user->canWriteToAlbum($gallery->album)) ||
                                    ($gallery->user->canChangeTextOfAlbum($gallery->album))) {
				$showAdminForm = 1;
			} else { 
				$showAdminForm = 0;
			}
			if ($showAdminForm) {
				$adminform = makeFormIntro("view_album.php", array("name" => "image_form_$i")); 
			}
			$caption = array();
			$id = $gallery->album->getPhotoId($i);
			if ($gallery->album->isHidden($i)) {
				$caption['status'] = '('._MD_GALLERY_HIDDEN.')';
			}
			if ($gallery->album->isAlbumName($i)) {
				$myAlbum = new Album();
				$myAlbum->load($gallery->album->isAlbumName($i));
				$myDescription = $myAlbum->fields['description'];
				$caption['title'] = _XG_ALBUM.': '.$myts->displayTarea($myts->stripSlashesGPC($myAlbum->fields['title']),1);
				if ($myDescription != _XG_NODESCRIPT) {
					$caption['description'] = $myDescription;
				}
				$caption['last_update'] = formatTimestamp($myAlbum->getLastModificationTime(), 'm');
				$caption['num_items'] = $myAlbum->numPhotos($gallery->user->canWriteToAlbum($myAlbum));
				if (!(strcmp($gallery->album->fields["display_clicks"] , _YES)) && ($myAlbum->getClicks() > 0)) {
				    $caption['num_views'] = $myAlbum->getClicks();
				}
			} else {
				// Get the xoops text sanitizer and clean text sent to browser from getCaption($i).
			    $myts =& MyTextSanitizer::getInstance();
				$caption['title'] = $myts->displayTarea($myts->stripSlashesGPC($gallery->album->getCaption($i)),1);
				$caption['index'] = $i;
				$photo = $gallery->album->getPhoto($i);
				$xoops_imageid = $photo->image->getXoopsImageId();
				// indicate with * if we have a comment for a given photo
				if (!empty($xoops_imageid) && is_object($album_images[$xoops_imageid])) {
					if (($xoopsModuleConfig['com_rule'] > 0) && ($gallery->album->fields["public_comments"] == _YES)) {
						$caption['num_comments'] = $album_images[$xoops_imageid]->getVar('image_comments');
					}
					$caption['last_update'] = formatTimestamp($album_images[$xoops_imageid]->getVar('image_created'), 'm');
				}
				if (!(strcmp($gallery->album->fields["display_clicks"] , _YES)) && ($gallery->album->getItemClicks($i) > 0)) {
			    	$caption['num_views'] = $gallery->album->getItemClicks($i);
				}
			}

			if ($showAdminForm) {
				if ($gallery->album->isMovie($id)) {
					$label = _XG_MOVIE;
				} elseif ($gallery->album->isAlbumName($i)) {
					$label = _XG_ALBUM1;
				} else {
					$label = _XG_PHOTO1;
				}
				$adminform .= "<select style='FONT-SIZE: 10px;' name='s' ".
					"onChange='imageEditChoice(document.image_form_$i.s)'>";
				$adminform .= "<option value=''>".sprintf(_XG_EDIT_PHOTO,$label)."</option>";
			}
			if ($gallery->user->canChangeTextOfAlbum($gallery->album)) {
				if ($gallery->album->isAlbumName($i)) {
					if ($gallery->user->canChangeTextOfAlbum($myAlbum)) {	
						$adminform .= showChoice(_XG_EDIT_TITLE, 
							"edit_field.php", 
							array("set_albumName" => $myAlbum->fields["name"],
								"field" => "title"));
						$adminform .= showChoice(_XG_EDIT_DESCRIPTION,
							"edit_field.php",
							array("set_albumName" => $myAlbum->fields["name"],
								"field" => "description"));
					}
					if ($gallery->user->isAdmin() || $gallery->user->isOwnerOfAlbum($myAlbum)) {
						$adminform .= showChoice(_XG_RENAME_ALBUM,
							"rename_album.php",
							array("set_albumName" => $myAlbum->fields["name"],
							      "index" => $i));
					}
				} else {
					$adminform .= showChoice(_XG_EDIT_CAPTION, "edit_caption.php", array("index" => $i));
				}
			}
			if ($gallery->user->canWriteToAlbum($gallery->album)) {
				if (!$gallery->album->isMovie($id) && !$gallery->album->isAlbumName($i)) {
					$adminform .= showChoice(_XG_CUSTOM_THUMBNAIL, "edit_thumb.php", array("index" => $i));
					$adminform .= showChoice(sprintf(_XG_ROTATE_LABEL,$label), "rotate_photo.php", array("index" => $i));
				}
				//if (!$gallery->album->isMovie($id)) {
					$adminform .= showChoice(sprintf(_XG_HIGHLIGHT_LABEL,$label), "highlight_photo.php", array("index" => $i));
				//}
				if ($gallery->album->isAlbumName($i)) {
				        $myAlbumName = $gallery->album->isAlbumName($i);

					$adminform .= showChoice(_XG_RESET_COUNTER, "do_command.php",
						array("cmd" => "reset-album-clicks",
						      "set_albumName" => $myAlbumName,
							"return" => urlencode(makeGalleryUrl("view_album.php"))));
				}
				$adminform .= showChoice(sprintf(_XG_MOVE_LABEL,$label), "move_photo.php", array("index" => $i));
				if ($gallery->album->isHidden($i)) {
					$adminform .= showChoice(sprintf(_XG_SHOW_LABEL,$label), "do_command.php", array("cmd" => "show", "index" => $i));
				} else {
					$adminform .= showChoice(sprintf(_XG_HIDDEN_LABEL,$label), "do_command.php", array("cmd" => "hide", "index" => $i));
				}
			}
			if ($gallery->user->canDeleteFromAlbum($gallery->album)) {
				if($gallery->album->isAlbumName($i)) { 
					if($gallery->user->canDeleteAlbum($myAlbum)) {
						$adminform .= showChoice(sprintf(_XG_DELETE_LABEL,$label), "delete_photo.php",
							array("id" => $myAlbum->fields["name"],
							      "albumDelete" => 1));
					}
				} else {
					$adminform .= showChoice(sprintf(_XG_DELETE_LABEL,$label), "delete_photo.php",
						   array("id" => $id));
				}
			}
			if($gallery->album->isAlbumName($i)) { 
			    if ($gallery->user->isAdmin() || $gallery->user->isOwnerOfAlbum($myAlbum)) {
				$adminform .= showChoice(_XG_PERMISSIONS,
					   "album_permissions.php",
					   array("set_albumName" => $myAlbum->fields["name"]));
			    }
			}
			if ($showAdminForm) {
				$adminform .= '</select></form>';
			}
			$captions[] =& $caption;
			$adminforms[] =& $adminform;
			unset($caption, $adminform);
			$j++;
			$i = getNextPhoto($i);
		}
		$xoopsTpl->append('picturerows', array('pictures' => $pictures, 'adminforms' => $adminforms, 'captions' => $captions));
		$rowCount++;
		$rowStart = $i;
	}
}
$xoopsTpl->assign('lang_lastupdate', _MD_GALLERY_LUPDATE);
$xoopsTpl->assign('lang_views', _MD_GALLERY_VIEWS);
$xoopsTpl->assign('lang_comments', _MD_GALLERY_COMMENTS);
$xoopsTpl->assign('lang_items', _MD_GALLERY_ITEMS);
$xoopsTpl->assign('lang_description', _DESCRIPTION);

include XOOPS_ROOT_PATH.'/footer.php';

?>